package org.seed.quantum.message.plugins;

import org.seed.quantum.socket.AbstractSocketSession;
import org.seed.quantum.socket.SocketClient;
import org.seed.quantum.socket.SocketStateEnum;
import java.nio.channels.AsynchronousChannelGroup;

public class ReconnectPlugin extends AbstractPlugin {



    private final AsynchronousChannelGroup asynchronousChannelGroup;
    private final SocketClient client;
    private boolean shutdown = false;

    public ReconnectPlugin(SocketClient client) {
        this(client, null);
    }

    public ReconnectPlugin(SocketClient client, AsynchronousChannelGroup asynchronousChannelGroup) {
        this.client = client;
        this.asynchronousChannelGroup = asynchronousChannelGroup;
    }

    @Override
    public void stateEvent(SocketStateEnum stateMachineEnum, AbstractSocketSession session, Throwable throwable) {
        if (stateMachineEnum != SocketStateEnum.SESSION_CLOSED || shutdown) {
            return;
        }
        try {
            if (asynchronousChannelGroup == null) {
                client.start();
            } else {
                client.start(asynchronousChannelGroup);
            }
        } catch (Exception e) {
            shutdown = true;
            e.printStackTrace();
        }

    }

    public void shutdown() {
        shutdown = true;
    }
}
